﻿package com.projects.xenia.documents_activities;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.projects.xenia.Activity_CustomersInfo;
import com.projects.xenia.Documents_Location;
import com.projects.xenia.MainCustomersListActivity;
import com.projects.xenia.R;
import com.projects.xenia.documents_classes.Documents_Blank;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.Documents_Location.GPSStateEnum;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class Activity_Blank extends Activity {
	
	private SimpleCursorAdapter adap;
	
	private Cursor BlanksCursor;
	private Cursor BlanksListCursor;
	
	private final Context Ctx = this;
	
	private Documents_Blank DocumentClass;
	
	private ImageView BlankGpsState;
	
	private Button BlankDate;	
	private Button BlankCustomer;
	
	private ListView DocBlankList;
	
	private final int IDR_CustomerSelect = 0;
	private final int IDR_BlankListSelect = 2;
	private final int IDR_GPSSettingsTest = 3;
	private final int IDR_MobileNetworkSettingsTest = 4;
	
	private int SelectedBlankListItemIndex;
	
	private ImageView blank_add;
	private ImageView exit_save;
	
	private SimpleCursorAdapter BlanksCursorAdapter;
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		return (DocumentClass);		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		MainGlobalModule.Documents_Location.StopLocation();
		MainGlobalModule.Documents_Location = null;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
	
		if (MainGlobalModule.SettingsCollection.get("ManagerId").equals("")) {
			Toast xtoast = Toast.makeText(this, "Устройство не авторизовано !!!", Toast.LENGTH_SHORT);
			xtoast.show();
			finish();
		}
		
		if (!MainGlobalModule.CheckLocationToday(true)) {
			finish ();
		}
		
		if (!MainGlobalModule.CheckGPSSettings(false)) {			
			startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
		}
		
		if (!MainGlobalModule.CheckMobileNetworkSettings()) {			
			startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS),IDR_MobileNetworkSettingsTest);
		}
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		setContentView(R.layout.blank_form);
		
		Bundle DocExtras;
		DocExtras = getIntent().getExtras();		
		
		DocumentClass = (Documents_Blank) getLastNonConfigurationInstance();
		
		if (DocumentClass== null) {			
			DocumentClass = new Documents_Blank ();			
			if (DocExtras!=null) {
				if (DocExtras.getString("DocId")!=null) {
					DocumentClass.OpenDoc(DocExtras.getString("DocId"));
					}
				else {
					DocumentClass.NewDoc();
					DocumentClass.Head.customers_id = DocExtras.getString("CustomerId");
					}
			}	
			else {
				DocumentClass.NewDoc();
			}			
		}
		
		BlankGpsState = (ImageView) findViewById(R.id.BlankGpsState);
		BlankGpsState.setVisibility(View.INVISIBLE);
		
		if (MainGlobalModule.Documents_Location==null) {
			MainGlobalModule.Documents_Location = new Documents_Location();
			MainGlobalModule.Documents_Location.StartLocation(this, MainGlobalModule.DocumentsType.Order, DocumentClass.Head.id,BlankGpsState);
		}
		
		
		BlankDate = (Button) findViewById(R.id.BlankDate);
		RefreshDate (BlankDate,DocumentClass.Head.date_create);
		
		BlankCustomer = (Button) findViewById(R.id.BlankCustomer);
		BlankCustomer.setOnClickListener(BlankCustomerSelect);
		BlankCustomer.setOnLongClickListener(CustomerLongSelect);
		RefreshByCursor (BlankCustomer , "xref_customers", DocumentClass.Head.customers_id);		
		
		
		GetBlanksListCursorByDocId (); 
		
		adap = new SimpleCursorAdapter(this, R.layout.listview_item ,BlanksListCursor , new String[] {"descr"}, new int[] {R.id.textView_question});
		DocBlankList = (ListView)findViewById(R.id.DocBlankList);
		DocBlankList.setAdapter(adap);
		
		DocBlankList.setOnItemLongClickListener(DocBlankList_OnItemLongClickListener);
		
		blank_add = (ImageView)findViewById(R.id.blank_add);
		blank_add.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				blank_add();
			}
		});
		
		exit_save = (ImageView)findViewById(R.id.exit_save);
		exit_save.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				exit_save ();				
			}
		});
		
	}
	
	private DialogInterface.OnClickListener DocBlankList_DialogListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    		    	
	    	BlanksListCursor.moveToPosition(SelectedBlankListItemIndex);
	    	
	    	switch (which) {
	    	
			case 0:
					    		
	    		Intent BlankListIntent = new Intent ();
	    		BlankListIntent.setClass(Ctx, Activity_BlankList.class);	    		
	    		MainGlobalModule.DocumentClass = DocumentClass;
	    		BlankListIntent.putExtra("BlankDescr", BlanksListCursor.getString(1));
	    		BlankListIntent.putExtra("BlankId", BlanksListCursor.getString(0));
	    		BlankListIntent.putExtra("DocId", DocumentClass.Head.id);    		
	    		startActivityForResult(BlankListIntent, IDR_BlankListSelect);		
				break;
				
			case 1:
			
				DocumentClass.DeleteByBlankId (BlanksListCursor.getString(0));
				BlanksListCursor.requery();
				
				break;
				
			}
	    }
	};
	
	private OnItemLongClickListener DocBlankList_OnItemLongClickListener = new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int position, long arg3) {
			
			SelectedBlankListItemIndex = position; 
			AlertDialog.Builder adb = new AlertDialog.Builder(Ctx);			
			adb.setItems(new String [] {"Редактировать","Удалить"} ,DocBlankList_DialogListener);
			Dialog alert = adb.create();
			alert.show(); 
					
			return true;
			
		}
		
	};
	
	private void RefreshDate (Button DateButton,Date DateValue) {
		
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
		DateButton.setText(sdf.format(DateValue));
		
	}	
	
	private void RefreshByCursor (Button SelectButton, String Table, String Id) {
		
		try {
			Cursor ScalarCursor = MainGlobalModule.DBE.query (Table, new String []{"descr"}, "id = ?", new String []{Id}, null, null, null);
			ScalarCursor.moveToFirst();
			SelectButton.setText(ScalarCursor.getString(0));
		} catch (Exception e) {
			SelectButton.setText ("");
		}
		
	}
	
	private OnClickListener BlankCustomerSelect= new OnClickListener () {	
		
		@Override
		public void onClick(View v) {			
			Intent CustomerSelectintent = new Intent();
			CustomerSelectintent.setClass(Ctx,MainCustomersListActivity.class);
			CustomerSelectintent.putExtra("customer_id", DocumentClass.Head.customers_id);
			CustomerSelectintent.putExtra("customer_descr","");
            startActivityForResult (CustomerSelectintent,IDR_CustomerSelect);			
		}
		
	};
	
	private OnLongClickListener CustomerLongSelect = new OnLongClickListener() {		
		@Override
		public boolean onLongClick(View v) {
			
			if (DocumentClass.Head.customers_id != null) {
				Intent CustomerInfoIntent = new Intent();
				CustomerInfoIntent.putExtra("CustomerId", DocumentClass.Head.customers_id);
				CustomerInfoIntent.setClass(Ctx,Activity_CustomersInfo.class);
		    	startActivity(CustomerInfoIntent);	
			}
			return true;
		}
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {	
		 
		 switch(requestCode) { 
		    case IDR_CustomerSelect:
		    	if (resultCode==RESULT_OK) {
		    		BlankCustomer.setText(data.getStringExtra("customer_descr"));
		    		DocumentClass.Head.state = 1;
		    		DocumentClass.Head.customers_id = data.getStringExtra("customer_id");
		    	}
		    	break;  	
		    case IDR_GPSSettingsTest:		    	
		    	if (!MainGlobalModule.CheckGPSSettings(false)) {			
		    		startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
		    	}		    	
		    	break;
		    case IDR_MobileNetworkSettingsTest:
		    	if (!MainGlobalModule.CheckMobileNetworkSettings()) {
		    		startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS),IDR_MobileNetworkSettingsTest);
		    	}
		    	break;
		    case IDR_BlankListSelect:		    
		    	adap.getCursor().requery();
		 }		 
		    	
	};	
	
    public boolean onCreateOptionsMenu (Menu menu){
    	
    	menu.add(Menu.NONE,1,Menu.NONE,"Добавить/Изменить");
    	menu.add(Menu.NONE,2,Menu.NONE,"Записать");
    	menu.add(Menu.NONE,3,Menu.NONE,"Выход");
    	
		return true;    	
    }
	
    
    private void GetBlanksCursorByDocId () {
    	
    	try {
    		BlanksCursor = MainGlobalModule.DBE.rawQuery("select distinct a.id as _id, a.descr as descr,b.hdoc_id from xref_blanks a left outer join xdoc_blanks_t b on a.id = b.blank_id and b.hdoc_id = ? order by a.descr ", new String [] {DocumentClass.Head.id});	
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    }

    private void GetBlanksListCursorByDocId () {
    	
    	try {
    		BlanksListCursor = MainGlobalModule.DBE.rawQuery("select distinct a.id as _id, a.descr as descr,b.hdoc_id from xref_blanks a inner join xdoc_blanks_t b on a.id = b.blank_id and b.hdoc_id = ? order by a.descr ", new String [] {DocumentClass.Head.id});	
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    }
    
    private DialogInterface.OnClickListener BlankSelectDialogListener = new DialogInterface.OnClickListener() {	
    	@Override
    	public void onClick(DialogInterface dialog, int which) {
    		
    		BlanksCursor.moveToPosition(which);
    		
    		Intent BlankListIntent = new Intent ();
    		BlankListIntent.setClass(Ctx, Activity_BlankList.class);
    		
    		MainGlobalModule.DocumentClass = DocumentClass;
    		BlankListIntent.putExtra("BlankDescr", BlanksCursor.getString(1));
    		BlankListIntent.putExtra("BlankId", BlanksCursor.getString(0));
    		BlankListIntent.putExtra("DocId", DocumentClass.Head.id);    		
    		startActivityForResult(BlankListIntent, IDR_BlankListSelect);		
    	}
    };
    
    private void blank_add () {
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	GetBlanksCursorByDocId ();		
		
		try {
			BlanksCursorAdapter	= new SimpleCursorAdapter(this, R.layout.listview_item_checked,BlanksCursor , new String[] {"descr"}, new int[] {R.id.checkedTextView1});    				
		} catch (Exception e) {
			e.printStackTrace();
		}    			
	

		builder.setTitle("Список анкет");
		builder.setAdapter(BlanksCursorAdapter, BlankSelectDialogListener);
		AlertDialog typPicker = builder.create();
		typPicker.show();
		
    }
    
    private void exit_save () {
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	
    	GPSStateEnum state = MainGlobalModule.Documents_Location.GetGPSState(DocumentClass.Head.id); 
		
		if (state != GPSStateEnum.accurate){
			
			
			String AddString = (state==GPSStateEnum.none?"Координата":"Точная координата");
			builder.setTitle(AddString.concat (" не определена !!! "));
			builder.setMessage("Хотите продолжить без определения ?");
			builder.setPositiveButton("Да,закрыть документ", new DialogInterface.OnClickListener() {    				    
				public void onClick(DialogInterface dialog, int which) {
					FinishActivity ();
			        dialog.dismiss();
			    }
			});

			builder.setNegativeButton("Нет,подождать", new DialogInterface.OnClickListener() {
			    @Override
			    public void onClick(DialogInterface dialog, int which) {
			        dialog.dismiss();
			    }
			});

			Dialog alert = builder.create();
			alert.show();    				
		}
		else
		{
			FinishActivity();
		}
    	
    }
    
    public boolean onOptionsItemSelected (MenuItem item){    	
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	
    	switch (item.getItemId()) {
    	
    		case 1:
    			
    			blank_add ();
    			break;    			
    			
    		case 3:
    			
    			exit_save();
    			
    			return true;
    			
    		case 2:  
    			DocumentClass.Head.state = 1;
    			DocumentClass.UpdateDoc();
    			return (true);
    			
    		}    		
    			return false;
    			
    }
   
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
		
		switch (keyCode){
		
    		case KeyEvent.KEYCODE_BACK:    			
    			return false;   			
    		
    	}	
		return super.onKeyDown(keyCode, event);
	}
	
 	public void FinishActivity () {
 		
 		DocumentClass.Head.state = 1;
    	DocumentClass.Head.verstamp++;
    	DocumentClass.UpdateDoc();
    	DocumentClass.FinishDoc ();
    	finish();    	
 			
 	}
 
}
